const { workModel } = require("../model");
const { checkpermission } = require("../utils/validate");
const uuid = require("uuid");
const defaultWorkParams = {
  select: "",
  populate: "",
  pageIndex: 0,
  pageSize: 10,
  customSort: { createdAt: -1 },
  find: {},
};
const { h5PagePath } = require("../config");
module.exports = {
  //根据id查询作品
  async getWorkByIdService(id) {
    return await workModel.findById(id).lean();
  },
  //创建作品
  async createWorkService(req, workProps) {
    const newWork = {
      ...workProps,
      uuid: uuid.v4(),
      user: req.info.id,
      author: req.info.username,
    };
    return await workModel.create(newWork);
  },
  //根据名称查询作品
  async getWorkByTitleService(title) {
    return await workModel.findOne({ title });
  },
  //查询作品列表
  async getWorkList(findParams) {
    const params = { ...defaultWorkParams, ...findParams };
    const { find, select, populate, pageIndex, pageSize, customSort } = params;
    const res = await workModel
      .find(find)
      .select(select)
      .sort(customSort)
      .skip(pageIndex * pageSize)
      .limit(pageSize)
      .populate(populate)
      .lean(); //lean()返回的是对象而不是mongoose文档
    const count = await workModel.find(find).countDocuments();
    return { res, count, pageIndex, pageSize };
  },
  //修改作品
  async updateWorkService(req, workProps) {
    const { id, userId } = workProps;
    const work = await workModel.find({ _id: id, user: userId });
    if (work.length === 0) {
      return null;
    }

    return await workModel
      .findOneAndUpdate({ _id: id }, req.body, {
        new: true,
      })
      .lean();
  },
  //删除作品
  async deleteWorkService(workProps) {
    const { id, userId } = workProps;
    const work = await workModel.find({ _id: id, user: userId });
    if (work.length === 0) {
      return null;
    }

    return await workModel
      .findOneAndDelete({ _id: id })
      .select(" _id id title ");
  },
  //发布作品或者模板，isTemplate为true时发布模板
  async publishWorkService(
    id,
    { isTemplate = false, isPublic = false },
    userId
  ) {
    console.log(id, isTemplate, userId);

    // const check = await checkpermission("workModel", id, userId);
    // if (!check) return null;
    const payload = {
      status: 2,
      ...(isTemplate && { isTemplate: true }),
      ...(isPublic && { isPublic: true }),
      lastEditTime: new Date(),
    };
    const res = await workModel
      .findByIdAndUpdate(id, payload, {
        new: true,
      })
      .lean();
    //http://114.55.1.185:3000
    const { uuid } = res;
    return `${h5PagePath}/api/utile/page/${res.id}-${uuid}`;
  },
  //复制作品
  async copyWorkService(req,id) {
    const work = await workModel.findById(id).lean();
    const { title,desc,coverImg,content  } = work;
    const data = await workModel.create({
      title,
      desc,
      coverImg,
      content,
      uuid: uuid.v4(),
      user: req.info.id,
      author: req.info.username,
    });
    return data;
  },
  /**
   * 创建渠道信息
   */
  async createChannelService(body) {
    const { id, name, channelUrl } = body;
    const workData = await workModel
      .findOneAndUpdate(
        { _id: id },
        { $push: { channel: { name, id: uuid.v4(), channelUrl } } },
        { new: true }
      )
      .lean();
    if (!workData) return null;
    return workData;
  },
  /**
   * 获取作品渠道信息
   */
  async getChannelListService(workId) {
    const { channel } = await workModel.findOne({ _id: workId }).lean();
    const channelList = [...channel];
    return channelList;
  },
  /**
   * 修改作品渠道信息
   */
  async updateChannelService({ channelId, name }) {
    const workData = await workModel
      .findOneAndUpdate(
        { "channel.id": channelId },
        { $set: { "channel.$.name": name } },
        { new: true }
      )
      .lean();
    return workData;
  },
  /**
   * 删除作品渠道信息
   */
  async deleteChannelService(channelId) {
    const workData = await workModel
      .findOneAndUpdate(
        { "channel.id": channelId },
        { $pull: { channel: { id: channelId } } },
        { new: true }
      )
      .lean();
    return workData;
  },
};
